package com.lkcg.demo.utils.api;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.log4j.Log4j;

import java.util.function.Function;
import java.util.function.Supplier;

@Log4j
@Data
@ApiModel(description = "API公共返回对象")
public class ResultObject<T> {

    @ApiModelProperty(value = "HTTP 状态码", name = "status", example = "200")
    private Long status = ResultStatus.OK;

    @ApiModelProperty(value = "通用状态代码", name = "code", example = "0")
    private Long code;

    @ApiModelProperty(value = "提示信息", name = "message", example = "成功")
    private String message;

    @ApiModelProperty(value = "返回数据", name = "data")
    private T data;

    public static <T> ResultObject<T> getResultObject(Supplier<T> s) {
        ResultObject<T> result = new ResultObject<T>();
        try {
            T t = s.get();
            result.setData(t);
            result.setResultCode(ResultCode.SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setResultCode(ResultCode.FAILURE);
        }

        return result;
    }

    public static <T> ResultObject<T> getResultObject(Function<ResultObject<T>, T> s) {
        ResultObject<T> result = new ResultObject<T>();
        try {
            T r = s.apply(result);

            if (result.getMessage() == null) {
                result.setData(r);
                result.setResultCode(ResultCode.SUCCESS);
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setResultCode(ResultCode.FAILURE);
        }

        return result;
    }

    public void setResultCode(ResultCode resultCode) {
        this.setMessage(resultCode.getValue());
        this.setCode(resultCode.getKey());
    }

}
